// modules dependences
import OpenAI from "openai";
const iconv = require('iconv-lite');
const { spawn } = require('child_process');
import config from './config.json';
import prompt from './prompt.json';
import { ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from "openai/resources/chat/completions";
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});


// call for DeepSeek platform
const openai = new OpenAI({
        baseURL: config.api_url,
        apiKey: config.api_key,
});

function get_prompt() {
    if (process.platform.startsWith('win')) {
        return prompt.prompt_win;
    } else if (process.platform.startsWith('darwin')) {
        return prompt.prompt_mac;
    } else {
        return prompt.prompt_linux;
    }
}

function exec_command(command: string) {
    let child;
    if (process.platform.startsWith('win')) {
        child = spawn('cmd.exe', ['/c '+command], {shell: true});
    } else {
        child = spawn(command, {shell: true});
    }

    // fetch result from command line
    child.stdout.on('data', (data) => {
        process.stdout.write(`${iconv.decode(data, 'gbk').trimRight()}`);
    });

    child.stderr.on('data', (data) => {
        console.error(`${iconv.decode(data, 'gbk').trimRight()}}`);
    });

    child.on('close', (code) => {
        console.log(`[RESULE CODE] ${code}`);
    });
}

const isPowerShell = () => {  
    // 检查操作系统平台  
    if (process.platform !== 'win32') {  
        return false;  // 只在 Windows 平台检查  
    }  
    // 检查 SHELL 环境变量  
    return process.env.SHELL && process.env.SHELL.includes("powershell");  
};  

const isCMD = () => {  
    // 检查操作系统平台  
    if (process.platform !== 'win32') {  
        return false;  // 只在 Windows 平台检查  
    }  
    // CMD 通常没有特殊的环境变量标识  
    return !process.env.SHELL; // 当没有 SHELL 环境变量时，认为是 CMD  
};  

function get_history() {
    let history = [];
    // 使用示例  
    if (isPowerShell()) {  
        console.log("当前是在 PowerShell 中");  
    } else if (isCMD()) {  
        console.log("当前是在 CMD 中");  
    } else {  
        console.log("当前不是在 CMD 或 PowerShell 中");  
    }  
    return history;
}

function question(base_cmd: ChatCompletionMessageParam[], message: ChatCompletionMessageParam) {
    // rl.on('line', (line) => {
    //     console.log(`[USER INPUT]: ${line}`);
    // });
    rl.question('(E)xplain the command or (R)eflush new command or (ENTER) to execute command immediately: ', async (input) => {
        switch (input.trim().toLowerCase()) {
        case 'e':
        case 'explain':
            {
                let last_cmd = base_cmd;
                base_cmd.push(message);
                base_cmd.push({ role: "user", content: prompt.explain });

                let param:ChatCompletionCreateParamsNonStreaming = {
                    model: "deepseek-chat",
                    messages: base_cmd,
                };
                const completion = await openai.chat.completions.create(param);

                // get command from AI platform
                let newMessage = completion.choices[0].message;
                let command = newMessage.content;
                if (command == null) {
                    console.log("Without response from AI platform, please check your network connection.");
                } else {
                    console.log("[AI RESPONSE]:", command);
                }
                
                // [todo] 这里竟然直接退出了, 需要解决为啥退出的原因
                question(last_cmd, message);
            }
        break;
        case 'r':
        case 'reflush':
            {
                base_cmd.push(message);
                base_cmd.push({ role: "user", content: prompt.reflush });
                let param:ChatCompletionCreateParamsNonStreaming = {
                    model: "deepseek-chat",
                    messages: base_cmd,
                };
                const completion = await openai.chat.completions.create(param);

                // get command from AI platform
                let newMessage = completion.choices[0].message;
                let command = newMessage.content;
                if (command == null) {
                    console.log("Without response from AI platform, please check your network connection.");
                } else {
                    console.log("[AI RESPONSE]:", command);
                }
                
                // [todo] 这里竟然直接退出了, 需要解决为啥退出的原因
                question(base_cmd, message);
            }
        break;
        case '':
            {   
                exec_command(message.content.toString());
                rl.close();
            }
        break;
        default:
            console.log('[UNKNOWN INPUT]');
        break;
        }
    });
}



// entry
async function main() {
    const args = process.argv;

    let chatLines:ChatCompletionMessageParam[] = [
        { 
            role: "system", 
            content: get_prompt(), 
        },
        { 
            role: "user", 
            content: args.slice(2)[0]
        }
    ];

    let param:ChatCompletionCreateParamsNonStreaming = {
        model: "deepseek-chat",
        messages: chatLines,
    };
    
    // call AI platform to get command
    const completion = await openai.chat.completions.create(param);

    // get command from AI platform
    let command = completion.choices[0].message.content;
    if (command == null) {
        console.log("Without response from AI platform, please check your network connection.");
    } else {
        console.log("[AI RESPONSE]:", command);

        question(chatLines, completion.choices[0].message);

        //rl.close();
    }
}

main();
